package com.seu.test.beans;

import com.seu.beans.Blue;
import com.seu.beans.Person;
import com.seu.config.MainConfigOfBeans;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.Map;

/**
 * Beans 相关注解测试
 *
 * @author liangfeihu
 * @since 2019/1/11
 */
public class IOCTestOfBeans {
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfBeans.class);

    @Test
    public void test01() {
        printBeanNames();
        printBeanInfoById("person");
        printBeanInfoByClass(Person.class);

        System.out.println("判断IOC容器中Bean是否是单例------");
        Object bean = applicationContext.getBean("person");
        Object bean2 = applicationContext.getBean("person");
        System.out.println(bean == bean2);
    }

    @Test
    public void test02() {
        String[] beanNamesForType = applicationContext.getBeanNamesForType(Person.class);
        for (String beanName : beanNamesForType) {
            System.out.println(beanName);
        }

        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        String property = environment.getProperty("os.name");
        System.out.println(property);

        Map<String, Person> persons = applicationContext.getBeansOfType(Person.class);
        System.out.println(persons);

    }

    @Test
    public void testImport() {
        printBeanNames();
        Blue bean = applicationContext.getBean(Blue.class);
        System.out.println(bean);

        //工厂Bean获取的是调用getObject创建的对象
        Object bean2 = applicationContext.getBean("colorFactoryBean");
        Object bean3 = applicationContext.getBean("colorFactoryBean");
        System.out.println("bean的类型：" + bean2.getClass());
        System.out.println(bean2 == bean3);

        Object bean4 = applicationContext.getBean("&colorFactoryBean");
        System.out.println(bean4.getClass());
    }


    private void printBeanNames() {
        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
        System.out.println("---------------bean names in IOC start-----------------");
        for (String name : beanDefinitionNames) {
            System.out.println(name);
        }
        System.out.println("---------------bean names in IOC end-----------------");
    }

    private void printBeanInfoById(String beanId) {
        Object bean = applicationContext.getBean(beanId);
        System.out.println(bean);
    }

    private void printBeanInfoByClass(Class beanClass) {
        Object bean = applicationContext.getBean(beanClass);
        System.out.println(bean);
    }
}
